import React from "react";
import "antd-mobile/dist/antd-mobile.css";
import {DatePicker, List, InputItem, Button, Modal, Toast} from "antd-mobile";
import ParkingSpace from "./ParkingSpace";
import "./index.css";
import {formatDate, validEmail} from "../../utils/common";
import Layout from "../Layout/Layout";
import Socket from "../../utils/socket";
const now = new Date();
const defaultArrivalTime = new Date(`${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} ${now.getHours() + 1}:00`);
const defaultLeaveTime = new Date(defaultArrivalTime.getTime() + 60 * 60 * 1000);
const isLicensePlate = /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/;
const maxTime = new Date(`${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate() + 3} ${now.getHours() + 1}:00`);
class ReserveStall extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            id: "",
            number: 21,
            arrivalTime: defaultArrivalTime,
            leaveTime: defaultLeaveTime,
            dpValue: null,
            carNumber: "",
            email: localStorage.getItem("email") || "",
            disabled: false,
            selectedSpaceId: "",
            isConnect: false
        };
        this.socket = new Socket({
            socketUrl: `${process.env.REACT_APP_BASE_WS}/real-time-parking/` + this.getId(),
            timeout: 5000,
            socketOpen: () => {
                this.setState({
                    isConnect: true
                });
                this.socket.sendMessage({
                    parkingLotId: this.getId(),
                    startTime: formatDate(this.state.arrivalTime),
                    endTime: formatDate(this.state.leaveTime),
                    command: "update"
                });
            },
            socketMessage: (receive) => {
                const data = JSON.parse(receive.data);
                if (data && data.parkingSpaceStatus) {
                    const currentStartTime = formatDate(this.state.arrivalTime);
                    const currentEndTime = formatDate(this.state.leaveTime);
                    const currentParkingLotId = this.getId();
                    if (currentEndTime === data.endTime && currentStartTime === data.startTime && data.parkingLotId === currentParkingLotId) {
                        this.props.updateSpaces(data.parkingSpaceStatus);
                    }
                }
            }
        });
        this.socket.connection();
    }

    // eslint-disable-next-line react/no-deprecated
    componentWillMount() {
        // eslint-disable-next-line react/prop-types
        this.setState({id: this.getId()});
    }

    getId=() => {
        return this.props.location.pathname.split("/")[2];
    }

    componentDidMount() {
        this.getParkingLotRealTimeMap().then();
    }

    setSelectedSpace = (flag, id) => {
        this.setState({
            selectedSpaceId: id
        });
    };

    onArrivalTimeChange = time => {
        this.setState({
            arrivalTime: time,
            leaveTime: new Date(time.getTime() + 60 * 60 * 1000)
        }, this.updateWithSocket);
    };

    updateWithSocket= async () => {
        const data = await this.getParkingLotRealTimeMap();
        if (this.state.isConnect && data) {
            this.socket.sendMessage({
                parkingLotId: this.getId(),
                ...data,
                command: "update"
            });
        }
    }

    onLeaveTimeChange = time => {
        this.setState({
            leaveTime: time
        }, this.updateWithSocket);
    };

    getParkingLotRealTimeMap = async () => {
        if (this.state.arrivalTime !== "" && this.state.arrivalTime !== "") {
            const data = {
                startTime: formatDate(this.state.arrivalTime),
                endTime: formatDate(this.state.leaveTime)
            };
            // eslint-disable-next-line react/prop-types
            await this.props.getAllSpacesByParklotId(this.state.id, data);
            return data;
        }
    };

    valid = () => {
        return validEmail(this.state.email) && isLicensePlate.test(this.state.carNumber);
    };

    toast = () => {
        const alert = Modal.alert;
        alert("信息有误", "请输入有效的车牌和邮箱！");
    };

    createReserveOrder = async () => {
        if (this.valid()) {
            localStorage.setItem("email", this.state.email);
            const data = {
                carNumber: this.state.carNumber,
                email: this.state.email,
                status: true,
                reserveParkingTime: formatDate(this.state.arrivalTime),
                reserveFetchingTime: formatDate(this.state.leaveTime),
                parkingLotId: this.state.id,
                parkingSpaceCode: this.state.selectedSpaceId
            };
            // eslint-disable-next-line react/prop-types
            await this.props.createReserveOrder(data).catch(() => {
                Toast.fail("创建订单是失败");
                // eslint-disable-next-line prefer-promise-reject-errors
                return Promise.reject("创建订单是失败");
            });
            this.socket.sendMessage({
                startTime: formatDate(this.state.arrivalTime),
                endTime: formatDate(this.state.leaveTime),
                parkingLotId: this.state.id,
                command: "create"
            });
            Toast.info("创建预约订单成功");
        } else {
            this.toast();
        }
    };

    setCarNumber = value => {
        this.setState({
            carNumber: value
        });
    };

    setEmail = value => {
        this.setState({
            email: value
        });
    };

    render() {
        return (
            <Layout {...this.props}>
                <div style={{background: "#fff"}}>
                    <DatePicker
                        minDate={defaultArrivalTime}
                        maxDate={maxTime}
                        value={this.state.arrivalTime}
                        onChange={this.onArrivalTimeChange}
                    >
                        <List.Item arrow="horizontal">预计到达时间</List.Item>
                    </DatePicker>

                    <DatePicker
                        value={this.state.leaveTime}
                        minDate={this.state.arrivalTime}
                        maxDate={maxTime}
                        onChange={this.onLeaveTimeChange}
                    >
                        <List.Item arrow="horizontal">预计离开时间</List.Item>
                    </DatePicker>
                    <div style={{padding: "1rem", display: "flex", background: "#fdfdfd"}}>
                        <div style={{flex: 3, height: "52vh", overflow: "auto", display: "flex", flexWrap: "wrap"}}>
                            {
                                this.props.spaces.map((value, index) => (
                                    <ParkingSpace space={value}
                                        isSelect={this.state.selectedSpaceId === value.parkingSpaceCode}
                                        key={index}
                                        setSelectedSpace={this.setSelectedSpace}/>
                                ))
                            }
                        </div>
                        <div style={{
                            flex: 1,
                            display: "flex",
                            flexDirection: "column",
                            justifyContent: "flex-start",
                            fontSize: "0.7rem",
                            alignItems: "center"
                        }}>
                            <div className={"item"}>
                                被占车位：
                                <span className={"item_tag"} style={{background: "#ea0000"}}/>
                            </div>
                            <div className={"item"}>
                                可选车位：
                                <span className={"item_tag"} style={{background: "#666"}}/>
                            </div>
                            <div className={"item"}>
                                选中车位：
                                <span className={"item_tag"} style={{background: "#1e8c02"}}/>
                            </div>
                            <div style={{marginTop: "1.8rem", fontWeight: "bold"}}>
                                剩余车位：{this.props.spaces.filter(item => !item.status).length}
                            </div>
                        </div>
                    </div>
                    <InputItem placeholder="请输入车牌号，如‘粤CJK761’"
                        value={this.state.carNumber}
                        onChange={this.setCarNumber}>
                        车牌号码
                    </InputItem>
                    <InputItem placeholder="请输入邮箱" value={this.state.email} onChange={this.setEmail}>邮箱</InputItem>
                    <div style={{display: "flex", justifyContent: "center"}}>
                        <Button size={"small"}
                            onClick={this.createReserveOrder}
                            inline
                            disabled={this.state.selectedSpaceId === "" || this.state.carNumber === "" || this.state.email === ""}>
                            预约
                        </Button>
                    </div>
                </div>
            </Layout>

        );
    }

    componentWillUnmount() {
        this.socket.close();
    }
}

export default ReserveStall;
